package com.authine.cloudpivot.ext.controller.workflow;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.authine.cloudpivot.web.api.controller.base.BaseController;
import com.authine.cloudpivot.web.api.dubbo.DubboConfigService;
import com.authine.cloudpivot.web.api.view.ResponseResult;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 二开待阅接口
 * 
 * @author shinka
 * @date 2021/06/30
 */
@Api(value = "待阅接口", tags = "01::EXTAPI::二开待阅接口")
@Controller
@RequestMapping("/public/ext/circulate")
public class CirculateItemController extends BaseController {

    private static Logger log = LoggerFactory.getLogger(CirculateItemController.class);

    @Autowired
    private DubboConfigService dubboConfigService;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @ApiOperation(value = "完成云枢系统的待阅任务")
    @PostMapping("/clear")
    @ResponseBody
    @ApiImplicitParams({
        @ApiImplicitParam(name = "userId", value = "云枢系统用户id，参数有值则清除当前用户的待办，反之遍历biz_circulateitem表",
            dataType = "String", paramType = "query"),
        @ApiImplicitParam(name = "date", value = "待阅开始时间(格式：2021-07-06)，如果参数有值则清除该时间以前（不含改时间）的待阅", dataType = "Date",
            paramType = "query")})
    public ResponseResult<Object> clearCirculateItem(@RequestParam(required = false) String userId,
        @RequestParam(required = false) String date) {
        log.debug("开始清理待阅任务, userId={},date={}", userId, date);
        try {
            Map<String, Object> paramMap = new HashMap<String, Object>();
            if (date.indexOf("-") == 4 && date.lastIndexOf("-") == 7) {
                // nothing
            } else {
                throw new Exception("时间格式错误，正确的如：2021-07-01");
            }
            // String startTime = new SimpleDateFormat("YYYY-MM-dd").format(new Date(date));
            String startTime = date;
            String sql = "select participant from biz_circulateitem";
            if (StringUtils.isEmpty(userId)) {
                if (!StringUtils.isEmpty(date)) {
                    sql = sql + " where DATE(startTime) <= :startTime ";
                    paramMap.put("startTime", startTime);
                }
            } else {
                sql = sql + " where participant =?";
                paramMap.put("userId", userId);
                if (!StringUtils.isEmpty(date)) {
                    sql = sql + " and DATE(startTime) < ? ";
                    paramMap.put("startTime", startTime);
                }
            }
            sql = sql + " group by participant;";
            log.debug("开始清理待阅任务, sql={}", sql);

            NamedParameterJdbcTemplate paramJdbcTemp = new NamedParameterJdbcTemplate(jdbcTemplate);
            List<Map<String, Object>> resultList = paramJdbcTemp.queryForList(sql, paramMap);

            // log.debug("resultList==" + resultList);
            if (CollectionUtils.isNotEmpty(resultList)) {
                for (int i = 0; i < resultList.size(); i++) {
                    Map<String, Object> map = resultList.get(i);
                    String participant = map.get("participant").toString();
                    try {
                        List<String> circulateItemIds = new ArrayList<>();
                        boolean result = dubboConfigService.getWorkflowInstanceFacade().updateCirculateRead(participant,
                            circulateItemIds);
                        long millis = 1 * 1000;
                        Thread.sleep(millis);
                        log.debug("[" + i + "]::result==" + result);
                    } catch (Exception e) {
                        // e.printStackTrace();
                        log.error("[" + i + "]::清除待阅失败，exception=" + e.toString());
                    }
                }
            }
            return getOkResponseResult(null, "任务下发成功");
        } catch (Exception e) {
            log.error("任务下发失败" + e.toString());
            return getErrResponseResult(null, null, "任务下发失败" + e.toString());
        }
    }

}
